package org.devocean.groupbuying.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.devocean.groupbuying.dao.MenuDAO;
import org.devocean.groupbuying.domain.Menu;
import org.devocean.groupbuying.domain.MenuLocalization;
import org.springframework.stereotype.Repository;

@Repository
public class MenuDAOImpl implements MenuDAO {

	@PersistenceContext
	private EntityManager em;

	public List<Menu> findAllMenus(String lang) {
		final Query query = em
				.createQuery(
						"SELECT m FROM Menu m LEFT JOIN FETCH m.menus ms LEFT JOIN FETCH m.menu mm WHERE m.lang=:lang and mm.menuLocalization.menuLocalizationID=1 ORDER BY m.menuLocalization.menuLocalizationID",
						Menu.class);

		query.setParameter("lang", lang);

		return query.getResultList();

	}

	public List<Menu> findAllMenus() {
		return em
				.createQuery(
						"SELECT m FROM Menu m  LEFT JOIN FETCH m.menu mm JOIN FETCH  m.menuLocalization ml",
						Menu.class).getResultList();
	}

	public Menu findMenuById(Integer id) {
		return em.find(Menu.class, id);
	}

	public void deleteMenu(int id) {
		final Menu menu = em.find(Menu.class, id);

		if (menu != null) {
			MenuLocalization menuLocalization = menu.getMenuLocalization();
			if (menuLocalization.getMenus().size() > 1) {
				menuLocalization.getMenus().remove(menu);
				em.remove(menu);
			} else
				em.remove(menuLocalization);
			em.flush();
		}
	}

	public Menu saveMenu(Menu menu) {
		em.persist(menu);
		em.flush();
		return menu;
	}

}
